import React, { useMemo, useCallback } from 'react';
import _get from 'lodash/get';
import _set from 'lodash/set';

const WrapPropToKeyPath = (
  Comp, 
  wrapTokeyPath, 
  {
    wrapToPropName = 'value',
    wrapToHandlerName = 'onChange',
    toWrapValue = v => v,
    compOriginalKey = 'value',
    compOriginalHandlerName = 'onChange',
    toOriginValue = v => v,
    defaultValue = undefined,
    containerStyle = {
      marginBottom: 24, // 和form-editor默认样式一致
    },
    labelStyle = {
      marginBottom: 4, // 和form-editor默认样式一致 
      // display: 'none', // 不需要label可以设置
    },
    extraProps = null,
  }
) => { 
  
  let keyPath = wrapTokeyPath;
  if (typeof keyPath === 'string') {
    keyPath = keyPath.split(',');
  }

  const hasKeyPath = keyPath && keyPath.length > 0;

  return (props) => {
    
    const {
      [wrapToPropName]: value,
      [wrapToHandlerName]: onChange,
      ...restProps
    } = props;

    const { label } = restProps;
   

    const compValue = useMemo(() => {
        return toOriginValue(hasKeyPath ? _get(value, keyPath, defaultValue) : (value !== undefined ? value : defaultValue));
    }, [value]);
  
    const compOnChange = useCallback((v) => {
      if (hasKeyPath) {
        const val = {...value};
        _set(val, keyPath, toWrapValue(v));
        onChange(val);
      } else {
        onChange(toWrapValue(v))
      }
   }, [onChange, value]);

    return (
      <div style={containerStyle}>
        <div style={labelStyle}>{label || ''}</div>
        <Comp 
          {...{
            [compOriginalKey]: compValue,
            [compOriginalHandlerName]: compOnChange,
            ...restProps,
            ...extraProps,
          }}
        />
      </div>
    );
  }
}

export default WrapPropToKeyPath;